package cn.icanci.loopstack.ddk.admin.biz.event.dict;

import cn.icanci.loopstack.ddk.admin.biz.service.AppConfigService;
import cn.icanci.loopstack.ddk.admin.biz.service.AppService;
import cn.icanci.loopstack.ddk.admin.biz.service.RegisterService;
import cn.icanci.loopstack.ddk.admin.biz.thread.TriggerThread;
import cn.icanci.loopstack.ddk.common.model.config.AppConfigVO;
import cn.icanci.loopstack.ddk.common.model.config.AppVO;
import cn.icanci.loopstack.ddk.common.model.config.RegisterVO;
import cn.icanci.loopstack.ddk.common.socket.publish.PublishTypeEnum;
import cn.icanci.loopstack.ddk.common.socket.publish.PublishValueRefreshDTO;
import cn.icanci.loopstack.ddk.common.socket.trigger.TriggerDTO;
import cn.icanci.loopstack.ddk.common.socket.trigger.ValueRefreshTriggerDTO;
import cn.icanci.loopstack.lsi.event.BaseEventListener;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

/**
 * 字典键发布
 * 
 * @author icanci
 * @since 1.0 Created in 2023/01/09 22:41
 */
@Service
public class DictEventListener extends BaseEventListener<DictEvent> {
    @Resource
    private AppService       appService;
    @Resource
    private AppConfigService appConfigService;
    @Resource
    private RegisterService  registerService;

    @Override
    protected void event(DictEvent event) {
        String uuid = event.getUuid();
        if (StringUtils.isBlank(uuid)) {
            return;
        }
        AppConfigVO appConfig = appConfigService.queryByUuid(uuid);
        if (appConfig == null) {
            return;
        }

        TriggerThread.trigger(buildTrigger(appConfig));
    }

    /**
     * 构建触发对象
     *
     * @param appConfig appConfig
     * @return 返回触发对象
     */
    private List<TriggerDTO> buildTrigger(AppConfigVO appConfig) {
        PublishValueRefreshDTO valueRefresh = new PublishValueRefreshDTO();
        valueRefresh.setKey(appConfig.getAppConfigName());
        valueRefresh.setValue(appConfig.getAppConfigValue());
        ValueRefreshTriggerDTO trigger = new ValueRefreshTriggerDTO();
        trigger.setPublishType(PublishTypeEnum.VALUE_REFRESH);
        trigger.setRegisters(queryRegister(appConfig));
        trigger.setValueRefresh(valueRefresh);
        return Lists.newArrayList(trigger);
    }

    private List<RegisterVO> queryRegister(AppConfigVO appConfig) {
        AppVO appVO = appService.queryByAppUuid(appConfig.getAppUuid());
        if (appVO == null) {
            return Lists.newArrayList();
        }
        return registerService.queryByAppId(appVO.getAppId());
    }
}
